<?php
/**
 *需要权限验证、需要登录验证公共基础类
 * User: raisound
 * Date: 2021/10/13
 */
namespace app\api\controller;
use app\common\model\redis\RedisModel;
class AuthBase  extends Base
{
    public $userId = 0;
    //当前请求的token
    public $xToken = "";
    public $groupId = "";
    public function initialize()
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: X-Token,Content-Type, Content-Length, Authorization, Accept, X-Requested-With, Current-Page');
        header('Access-Control-Allow-Methods: POST,GET,OPTIONS,DELETE,PUT');
        parent::initialize();
        $this->xToken = $this->request->header(config("config.head.token"));
        if(!$this->xToken){
            return $this->returnResult(config("config.code.not_login"),'请输入token！');
        }
        if(!$this->isLogin()){
            return $this->returnResult(config("config.code.not_login"),'token失效！');
        }
    }


    /**
     * 判断用户是否已登陆
     * @return bool
     */
    public function isLogin(): bool
    {
        $RedisModel = new RedisModel();
        $userInfo = $RedisModel->getValue(config("redis.token_pre").$this->xToken);
        $userInfo = json_decode($userInfo,true);
        if(empty($userInfo)){
            return false;
        }
        // 更新token时间
        $userInfo = \app\api\business\AdminBus::heartbeat($this->xToken);
        if(empty($userInfo) || empty($userInfo['id']) || empty($userInfo['group_id'])){
            return false;
        }else{
            $this->userId = $userInfo['id'];
            $this->groupId = $userInfo['group_id'];
            return true;
        }
    }

}
